var superviseTimer;
var taskQueue=[];
var userid=1;
var urlBase = "/dldsj/parallel";

//获取用户的正在进行的并行任务状态，并初始化监控列表
function getPersonalJobStat(userid) {
    if (!userid) {
        alert("未查询到用户信息");
    }
    $.ajax({
        url: urlBase + "parallelModelsJobRecord/running/" + userid,
        method: "get",
        success: function (res) {
            if (res) {
                var result = JSON.parse(res);
                for (var i = result.length - 1; i >= 0; i--) {
                    if (taskQueue.findIndex(function (value) {
                            return value.name === result[i].applicationid;
                        }) > -1)
                        continue;//跳过已加载的记录
                    var task = {};
                    task.name = result[i].applicationid;
                    task.taskname = result[i].remarks;
                    task.modelId = result[i].toolid;
                    task.modelName = result[i].toolid;
                    if (result[i].toolname) {
                        task.modelName = result[i].toolname;
                    }
                    task.outputType = result[i].outputType;
                    task.regioncode = "lost";
                    task.regionname = "lost";
                    addTaskItem(task);
                }
            }
        }
    });
}

/**
 * 添加并行任务至临时任务列表，并添加监控
 * 在添加并行任务时记录该任务的结果输出类型
 * 任务输出类型：
 *            output_map_dltj                    ->        xml:thematic.map.dltj
 *            output_chart_dltj                ->        xml:thematic.chart.dltj
 *            output_show                        ->
 *            output_download                    ->        xml:download
 *            output_map_centrepoint_dltj        ->        xml:thematic.map.centrepoint.dltj
 *            output_chart_centrepoint_dltj    ->        xml:thematic.chart.centrepoint.dltj
 *            output_map_centrepoint            ->        xml:thematic.map.centrepoint
 *            output_chart_centrepoint        ->        xml:thematic.chart.centrepoint
 *            output_chart_demstat            ->        xml:thematic.chart.demstat
 **/
function addTaskItem(task) {
    // task.output_map_centrepoint = "none";
    // task.output_map = "none";
    // task.output_chart = "none";
    // task.output_show = "none";
    task.output_download = "inline";

    taskQueue.push(task);
    // $("#taskList").parent().find(".temp_blank").remove();
    // $("#mis_name").value = task.name;
    // $("#modal_name").value = task.name;
    // $("#taskList").find("li").attr("name").value = task.name;


    listr = "<li  style=\"height:15%;margin-left:-41px;background:#fff;border-bottom: 1px solid #ddd;border-right: 1px solid #ddd;border-left: 1px solid #ddd;\"  name=\"" + task.name + "\" appId=\"" + task.name + "\">\n" +
        "                      <div class=\"parallel-tasklist\"\n" +
        "                           style=\"margin-top:0px; padding-top:0px;height: 15%;\">\n" +
        "                          <i id='task_status' class=' fa-lg fa fa-cog' style=\"float:left;color:#ccc333;padding:10px;\"\n" +
        "                             title='等待提交'></i>\n" +
        "                          <div class=\"text-overflow parallel-tasklist parallel-tasklist-left\"\n" +
        "                               style=\"float:left;width:220px;color:#ccc222;padding:8px 0 0 0;\" title=\"{{this.taskname}}\">\n" +
        "                              任务名称：<p  style=\"color:#2bd6ff;padding-left:83px;margin-top:-20px;font-size: x-small\">"+ task.name +"</p>\n" +
        "                          </div>\n" +
        "                          <br/>\n" +
        "                          <div class=\"text-overflow parallel-tasklist parallel-tasklist-left\"\n" +
        "                               style=\"margin-left: 39px;float:left;width:300px;color:#262626\" title=\"{{this.modelId}}\">\n" +
        "                              模型名称：<label  style=\"color:#94ffc0;font-size: x-small\">" + task.name.split("1")[0] + "</label>\n" +
        "                          </div>\n" +
        "                          <br/>\n" +
        "                          <div class=\"parallel-tasklist\">\n" +
        "                              <label class=\"\" style=\"float:left;padding-top:25px; margin-left:-300px;color:#bc6ccc\">\n" +
        "                                  进度监控：\n" +
        "                              </label>\n" +
        "                              <div class='progress progress-striped active'\n" +
        "                                   style='width: 120px;float:left;margin:26px 0 0 -215px;' title=\"任务进度\">\n" +
        "                                  <div class='parallel-tasklist progress-bar progress-bar-warning' aria-valuemax=\"100\"\n" +
        "                                       aria-valuemin=\"0\" aria-valuenow=\"0\" style='width: 0%;'></div>\n" +
        "                              </div>\n" +
        "                              <div style='width: 130px;float:right;padding:26px 10px 0 0;color:#cc22cc'>\n" +
        "                                  <i id='task_output_download'\n" +
        "                                     style=\"display: {{this.output_download}};float:right;padding-right:2px;\"\n" +
        "                                     class='fa-lg fa fa-download download' title='下载结果' path='{{this.name}}'\n" +
        "                                     taskname='{{this.modelName}}' regioncode='{{this.regioncode}}'\n" +
        "                                     regionname='{{this.regionname}}' onclick='downloadResult(\"" + task.name + "\")'></i>\n" +
        "                                  </div>\n" +
        "                          </div>\n" +
        "                      </div>\n" +
        "                  </li>";


    //解析填入
    // var template = Handlebars.compile(source);
    // var taskItem = $(template(task));
    // taskItem.find("#refresh").hide();
    // taskItem.find("i[id^='task_output']").click(function () {
    //     //激活结果展示的按钮
    //     activeOutputButtons(this);
    // });
    // taskItem.find("#task_kill").click(function () {
    //     if ($(this).hasClass("task-kill-active")) {
    //         debugger;
    //         var taskname = $(this).parent().parent().attr("name");
    //         var appId = $(this).parent().parent().attr("appId");
    //         $.ajax({
    //             url: urlBase + "parallelModels/kill/" + appId,
    //             method: "delete",
    //             success: function (res) {
    //                 var result = JSON.parse(res);
    //                 if (result.status === "true")
    //                     alert("任务" + taskname + "已经终止");
    //                 else
    //                     alert("任务" + taskname + "终止失败");
    //             }
    //         });
    //     }
    // });
    $("#taskList").prepend(listr);
    beginSupervise();
}



// 监听并行任务的方法
function supervise() {
    if (taskQueue.length === 0) {
        clearInterval(superviseTimer);
        superviseTimer = null;
        return;
    }

    $(taskQueue).each(function (i, task) {
        // console.debug(task.name);
        var taskItem = $("#taskList>li[name='" + task.name + "']");
        $.ajax({
            url: urlBase + "/monitor/" + task.name,
            type: "get",
            dataType: "json",
            success: function (app) {
                app = app.body;
                taskItem.find(".progress-bar").css("width", app.progress + "%");
                taskItem.attr("appId", app.id);
                translateProgress(taskItem, app.state);
                // 如果当前状态不为accepted，且监听状态为accepted，则提示用户任务接受
                if (app.state === "ACCEPTED" && taskItem.attr("state") !== "ACCEPTED") {
                    taskItem.attr("state", "ACCEPTED");
                    alert("任务" + app.name + "已被后台接收");
                }
                // 如果当前状态为ACCEPTED，且监听状态为RUNNING，则提示用户任务开始运行
                else if (app.state === "RUNNING" && taskItem.attr("state") !== "RUNNING") {
                    taskItem.attr("state", "RUNNING");
                    alert("任务" + app.name + "已经开始执行");
                }
                // 如果当前状态为RUNNING，且监听状态为FINISHED，则提示用户任务运行完毕
                else if (app.state === "FINISHED" && taskItem.attr("state") !== "FINISHED") {
                    taskItem.attr("state", "FINISHED");
                    alert("任务" + app.name + "已经结束,最终运行结果为:" + translateFinalState(taskItem, app.finalStatus));
                    taskItem.find("#task_kill").removeClass("active");
                    taskItem.find(".uk-progress").removeClass("uk-progress-striped").addClass("uk-progress-success");
                    taskQueue.splice(i, 1);
                }
                else if (app.state === "KILLED" && taskItem.attr("state") !== "KILLED") {
                    taskItem.attr("state", "KILLED");
                    alert("任务" + app.name + "已经结束,最终运行结果为:" + translateFinalState(taskItem, app.finalStatus));
                    taskQueue.splice(i, 1);
                } else if (app.state === "FAILED" && taskItem.attr("state") !== "FAILED") {
                    taskItem.attr("state", "FAILED");
                    alert("任务" + app.name + "已经结束,最终运行结果为:" + translateFinalState(taskItem, app.finalStatus));
                    taskQueue.splice(i, 1);
                }
                if (taskQueue.length === 0) {
                    superviseTimer = null;
                }
            }
        });
    });
}

// 开始监听并行计算任务
function beginSupervise() {
    if (superviseTimer) {
        return;
    }
    supervise();
    superviseTimer = setInterval(function () {
        supervise();
    }, 5000);
}



// 并行任务状态解析
function translateProgress(target, engState) {
    switch (engState) {
        case "RUNNING":
            $(target).find("#task_status")
                .attr("title", "正在运行")
                .addClass("fa fa-spin")
                .css("color", "orange");
            $(target).find("#task_kill").addClass("task-kill-active");
            $(target).find("#task_output_submitinfo").addClass("task-result-active");
            break;
        case "FINISHED":
            $(target).find("#task_status")
                .attr("title", "运行完毕")
                .attr("class", "")
                .addClass("fa fa-circle")
                .css("color", "green");
            break;
        case "ACCEPTED":
            $(target).find("#task_status")
                .attr("title", "已被后台接收")
                .addClass("fa fa-spin");
            $(target).find("#task_kill").addClass("task-kill-active");
            break;
        default:
            $(target).find("#task_status")
                .addClass("fa fa-spin");
            break;
    }

}

// 并行任务处理结果解析
function translateFinalState(target, engState) {
    var state = "";
    switch (engState) {
        case "FAILED":
            $(target).find("i[id^='task_output']").removeClass("task-result-active");
            $(target).find("#task_status")
                .attr("title", "运行失败")
                .attr("class", "")
                .addClass("fa fa-circle")
                .css("color", "#ff4d4d");
            $(target).find("#task_kill").removeClass("task-kill-active");
            $(target).find(".progress").removeClass("progress-striped").addClass("progress-danger");
            state = "运行失败";
            break;
        case "SUCCEEDED":
            $(target).find("i[id^='task_output']").addClass("task-result-active");
            $(target).find("#task_kill").removeClass("task-kill-active");
            state = "运行成功";
            break;
        case "KILLED":
            $(target).find("i[id^='task_output']").removeClass("task-result-active");
            $(target).find("#task_status")
                .attr("title", "终止运行")
                .attr("class", "")
                .addClass("fa fa-circle")
                .css("color", "#ff4d4d");
            $(target).find("#task_kill").removeClass("task-kill-active");
            $(target).find(".progress").removeClass("progress-striped").addClass("progress-danger");
            state = "终止运行";
            break;
        case "UNACCEPTED":
            $(target).find("i[id^='task_output']").removeClass("task-result-active");
            $(target).find("#task_status")
                .attr("title", "运行失败")
                .attr("class", "")
                .addClass("fa fa-circle")
                .css("color", "#ff4d4d");
            $(target).find("#task_kill").removeClass("task-kill-active");
            $(target).find(".progress").removeClass("progress-striped").addClass("progress-danger");
            state = "运行失败";
            break;
        default:
            break;
    }
    return state;
}

function downloadResult(applicationId) {
    debugger;
    // window.location.href = urlBase + "parallelModels/download/" + applicationId;
    window.open(urlBase + "/result/download/" + applicationId);
}

